<?php if(!defined('BASEPATH')) exit('No direct script access allowed');

class Import extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->common_model->checkpurview();
        $this->load->helper('download');
        $this->load->library('excel/excel_reader2');
        $this->load->library('pinyin/getpinyin');
    }

    public function index()
    {
        $dir = './data/upfile/' . date('Ymd') . '/';
        $err = json_encode(array('url' => '', 'title' => '', 'state' => '请登录'));
        $info = upload('resume_file', $dir);
        if(is_array($info) && count($info) > 0)
        {
            print_r($info);
            die();
        }
        else
        {
            die($err);
        }
    }

    /**
     * 下载客户模板
     * @author longli
     */
    public function downloadtemplate1()
    {
        $info = read_file('./data/download/customer.xls');
        $this->common_model->logs('下载文件名:客户导入_' . date("YmdHis") . '.xls');
        force_download('客户导入_' . date("YmdHis") . '.xls', $info);
    }

    /**
     * 下载供应商模板
     * @author longli
     */
    public function downloadtemplate2()
    {
        $info = read_file('./data/download/vendor.xls');
        $this->common_model->logs('下载文件名:供应商导入_' . date("YmdHis") . '.xls');
        force_download('供应商导入_' . date("YmdHis") . '.xls', $info);
    }

    /**
     * 下载商品模板
     * @author longli
     */
    public function downloadtemplate3()
    {
        $info = read_file('./data/download/goods.xls');
        $this->common_model->logs('下载文件名:商品导入_' . date("YmdHis") . '.xls');
        force_download('商品导入_' . date("YmdHis") . '.xls', $info);
    }

    public function findDataImporter()
    {

    }

    public function upload()
    {

    }

    /**
     * 导入商品，客户，供应商
     * @author longli
     */
    public function uploadExcel()
    {
        $path = $_FILES['file'];
        if($path['error'] != 0)
            str_alert(-1, '文件上传失败！');
        if($path['size'] > 20 * 1024 * 1024)
            str_alert(-1, '上传文件大小超过限制！');
        $suffix = substr(strrchr($path['name'], '.'), 1);
        if(!in_array($suffix, ['xls']))
            str_alert(200, '上传的文件不是excel类型！');
        $filePath = "data/upload/" . date('YmdHis') . rand(1000, 9999) . ".xls";
        move_uploaded_file($path["tmp_name"], $filePath);

        $reader = $this->excel_reader2;
        $reader->setOutputEncoding("utf-8");    // 设置编码方式
        $reader->read($filePath);
        $data = $reader->sheets[0]['cells'];
        if(!isset($data[2]) || !isset($data[2][1]))
            str_alert(-1, '无可导入的数据！');
        $first = array_shift($data);
        $itype = "";
        $this->db->trans_begin();
        if(trim($first[1]) == '商品编号')
        {
            $this->uploadGoods($data);
            $itype = "商品";
        }
        else if($first[1] == '客户编号')
        {
            $itype = "客户";
            foreach($data as $arr => $row)
            {
                $row = array_map(function($item) {
                    return trim($item);
                }, $row);
                $cust['number'] = $row[1];
                $cust['name'] = $row[2];
                //$cust['cCategory'] = $row[3];
                //$cust['cCategoryName'] = $row[4];
                $cust['cLevel'] = 0;
                $cust['remark'] = $row[8];
                $linkMan['linkName'] = $row[9];
                $linkMan['linkMobile'] = $row[10];
                $linkMan['linkPhone'] = $row[11];
                $linkMan['linkPlace'] = $row[12];
                $linkMan['linkIm'] = $row[13];
                $linkMan['linkFirst'] = 1;
                $linkMan['id'] = 0;
                $linkMans[0] = $linkMan;
                $cust['linkMans'] = json_encode($linkMans);
                $cust['type'] = -10;
                empty($row[1]) && str_alert(-1, '第' . $arr . '行客户编号不能为空！');
                empty($row[2]) && str_alert(-1, '第' . $arr . '行客户名称不能为空！');
                empty($row[3]) && str_alert(-1, '第' . $arr . '行客户类别不能为空！');
                $list = $this->mysql_model->get_rows('category', array('name' => $row[3], 'typeNumber' => 'customertype'));
                if(count($list) > 0)
                {
                    $cust['cCategory'] = $list['id'];
                    $cust['cCategoryName'] = $row[3];
                }
                else
                {
                    str_alert(-1, '第' . $arr . '行客户类别【' . $row[3] . '】不存在,请先添加客户类别再导入！');
                }

                $info = array(
                    'number', 'name', 'cLevel', 'remark', 'cCategory', 'cCategoryName', 'linkMans', 'type'
                );
                $info = elements($info, $cust, NULL);

                if($this->mysql_model->get_count('contact', array('isDelete' => 0, 'number' => $cust['number'])) <= 0)
                {
                    $rtn['id'] = $this->mysql_model->insert('contact', $info);
                }
                else
                {
                    $this->mysql_model->update('contact', $info, array('number' => $cust['number']));
                }
            }
        }
        else if($first[1] == '供应商编号')
        {
            $itype = "供应商";
            foreach($data as $arr => $row)
            {
                $row = array_map(function($item) {
                    return trim($item);
                }, $row);
                $sup['number'] = $row[1];
                $sup['name'] = $row[2];
                //$cust['cCategory'] = $row[3];
                //$cust['cCategoryName'] = $row[4];
                $sup['cLevel'] = 0;
                $sup['remark'] = $row[7];
                $linkMan['linkName'] = $row[8];
                $linkMan['linkMobile'] = $row[9];
                $linkMan['linkPhone'] = $row[10];
                $linkMan['linkPlace'] = $row[11];
                $linkMan['linkIm'] = $row[12];
                $linkMan['linkFirst'] = 1;
                $linkMan['id'] = 0;
                $linkMans[0] = $linkMan;
                $sup['linkMans'] = json_encode($linkMans);
                $sup['type'] = 10;
                empty($row[1]) && str_alert(-1, '第' . $arr . '行供应商编号不能为空！');
                empty($row[2]) && str_alert(-1, '第' . $arr . '行供应商名称不能为空！');
                empty($row[3]) && str_alert(-1, '第' . $arr . '行供应商类别不能为空！');
                $list = $this->mysql_model->get_rows('category', array('name' => $row[3], 'typeNumber' => 'supplytype'));
                if(count($list) > 0)
                {
                    $sup['cCategory'] = $list['id'];
                    $sup['cCategoryName'] = $row[3];
                }
                else
                {
                    str_alert(-1, '第' . $arr . '行供应商类别【' . $row[3] . '】不存在,请先添加供应商类别再导入！');
                }

                $info = array(
                    'number', 'name', 'cLevel', 'remark', 'cCategory', 'cCategoryName', 'linkMans', 'type'
                );
                $info = elements($info, $sup, NULL);

                if($this->mysql_model->get_count('contact', array('isDelete' => 0, 'number' => $sup['number'])) <= 0)
                {
                    $rtn['id'] = $this->mysql_model->insert('contact', $info);
                }
                else
                {
                    $this->mysql_model->update('contact', $info, array('number' => $sup['number']));
                }
            }
        }
        if($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            str_alert(-1, 'SQL错误回滚');
        }
        else
        {
            $this->db->trans_commit();
            str_alert(200, '恭喜您，导入' . $itype . '信息成功！');
        }
    }

    /**
     * 上传产品
     * @param array $data 产品数据
     * @author longli
     */
    private function uploadGoods($data)
    {
        $data = $this->assemblyGoods($data);
        // echo json_encode($this->validateGoods($data));exit;
        foreach($this->validateGoods($data) as $sku => $goods)
        {
            $invId = $this->mysql_model->insert('goods', $goods['goodsData']);
            if(!empty($goods['warehouse']))
            {
                foreach($goods['warehouse'] as &$w)
                    $w['invId'] = $invId;
                $this->mysql_model->insert('warehouse', $goods['warehouse']);
            }
            foreach($goods['goodsInfo'] as &$g)
                $g['invId'] = $invId;
            $this->mysql_model->insert('invoice_info', $goods['goodsInfo']);
        }
    }

    // 分类列表
    private $category;

    // 仓库列表
    private $storage;

    // 单位列表
    private $unit;

    /**
     * 验证上传产品数据
     * @param array $data 验证数据
     * @return array
     * @author longli
     */
    private function validateGoods($data)
    {
        $ret = [];
        $this->category = $this->mysql_model->get_results_by_index('category', 'name', ['typeNumber' => 'trade', 'isDelete' => 0]);
        $this->storage = $this->mysql_model->get_results_by_index('storage', 'name', ['isDelete' => 0]);
        $this->unit = $this->mysql_model->get_results_by_index('unit', 'name', ['isDelete' => 0]);
        foreach($data as $sku => $item)
        {
            $row = array_shift($item);
            $this->validateItem($row);
            $lowQty = floatval($row[8]);
            $highQty = floatval($row[9]);
            $goodsInfo = $properties = $warehouseProperties = $warehouse = [];
            foreach($item as $gk => $gs)
            {
                !empty($gs[23]) && !$this->storage[$gs[23]] && str_alert(-1, "$sku 的{$gs[23]}仓库不存在");
                !empty($gs[23]) && !empty($row[24]) && (!is_numeric($gs[24]) || $gs[24] <= 0) && str_alert(-1, "$sku {$gs[23]}期初数量输入有误");
                !empty($gs[23]) && !empty($row[25]) && (!is_numeric($gs[25]) || $gs[25] <= 0) && str_alert(-1, "$sku {$gs[23]}成本输入有误");
                !empty($gs[23]) && !empty($row[26]) && (!is_numeric($gs[26]) || $gs[26] <= 0) && str_alert(-1, "$sku {$gs[23]}期初总价输入有误");

                if(!empty($gs[8]))
                {
                    $lowQty = 0;
                    $warehouse[$gk]['lowQty'] = $gs[8];
                    $warehouse[$gk]['locationId'] = $this->storage[$gs[23]]['id'];
                }
                if(!empty($gs[9]))
                {
                    $highQty = 0;
                    $warehouse[$gk]['highQty'] = $gs[9];
                    $warehouse[$gk]['locationId'] = $this->storage[$gs[23]]['id'];
                }
                $warehouseProperties[] = [
                    'locationId' => $this->storage[$gs[23]]['id'],
                    'locationName' => $gs[23],
                    'highQty' => $gs[8],
                    'lowQty' => $gs[9],
                ];
                $amount = !empty($gs[26]) ? $gs[26] : floatval($gs[24]) * floatval($gs[25]);
                $properties[] = [
                    "locationId" => $this->storage[$gs[23]]['id'],
                    "quantity" => floatval($gs[24]),
                    "unitCost" => floatval($gs[25]),
                    "amount" => $amount,
                    "batch" => "",
                    "prodDate" => "",
                    "safeDays" => "",
                    "validDate" => "",
                    "id" => rand(1000, 10000),
                ];

                $goodsInfo[] = [
                    'billNo' => '期初数量',
                    'amount' => $amount,
                    'billDate' => date('Y-m-d'),
                    'invId' => '', // 关联商品id
                    'price' => $gs[25],
                    'qty' => $gs[24],
                    'locationId' => $this->storage[$gs[23]]['id'],
                    'transTypeName' => '期初数量',
                    'billType' => 'INI',
                ];
            }

            // 添加主产品
            $amount = !empty($row[26]) ? $row[26] : floatval($row[24]) * floatval($row[25]);
            $goodsInfo[] = [
                'billNo' => '期初数量',
                'amount' => $amount,
                'billDate' => date('Y-m-d'),
                'invId' => '', // 关联商品id
                'price' => $row[25],
                'qty' => $row[24],
                'locationId' => $this->storage[$row[23]]['id'],
                'transTypeName' => '期初数量',
                'billType' => 'INI',
            ];

            $warehouseProperties[] = [
                'locationId' => $this->storage[$row[23]]['id'],
                'locationName' => $row[23],
                'highQty' => $row[8],
                'lowQty' => $row[9],
            ];
            $properties[] = [
                "locationId" => $this->storage[$row[23]]['id'],
                "quantity" => floatval($row[24]),
                "unitCost" => floatval($row[25]),
                "amount" => $amount,
                "batch" => "",
                "prodDate" => "",
                "safeDays" => "",
                "validDate" => "",
                "id" => rand(1000, 10000),
            ];
            if(!empty($warehouse))
            {
                $warehouse[] = [
                    'highQty' => floatval($row[9]),
                    'lowQty' => floatval($row[8]),
                    'locationId' => $this->storage[$row[23]]['id'],
                ];
            }
            $goodsData = [
                'name' => $row[2],
                'number' => $row[1],
                'spec' => $row[5],
                'unitName' => $row[6],
                'baseUnitId' => $this->unit[$row[6]]['id'],
                'categoryId' => $this->category[$row[4]]['id'],
                'categoryName' => $row[4],
                'purPrice' => floatval($row[10]),
                'salePrice' => floatval($row[11]),
                'wholesalePrice' => $row[12],
                'remark' => $row[19],
                'disable' => 0,
                'propertys' => json_encode($properties),
                'vipPrice' => $row[13],
                'lowQty' => $lowQty,
                'highQty' => $highQty,
                'barCode' => $row[3],
                'discountRate1' => $row[14] == 0 ? 0 : ($row[14] < 10 ? "{$row[14]}0" : $row[14]),
                'discountRate2' => $row[15] == 0 ? 0 : ($row[15] < 10 ? "{$row[15]}0" : $row[15]),
                'locationId' => $this->storage[$row[7]]['id'],
                'locationName' => $row[7],
                // 'pinYin'          => $pinYing($row[2]),
                'warehousePropertys' => json_encode($warehouseProperties),
                'declareCn' => !empty($row[19]) ? $row[19] : '',
                'declareEn' => !empty($row[20]) ? $row[20] : '',
                'declarePrice' => floatval($row[21]),
                'length' => $row[16],
                'width' => $row[17],
                'height' => $row[18],
                'warehouseWarning' => !empty($warehouse) ? 1 : 0,
            ];
            $ret[$sku] = compact('goodsData', 'warehouse', 'goodsInfo');
        }
        return $ret;
    }

    /**
     * 单行数据验证
     * @param array $row
     * @author longli
     */
    private function validateItem($row)
    {
        $sku = $row[1];
        $this->data_model->check_goods_exist('number', $row[1]) && str_alert(-1, "$sku 商品编码已使用过");
        $this->data_model->check_goods_exist('name', $row[2]) && str_alert(-1, "$sku 商品名称已使用过");
        !empty($row[3]) && $this->data_model->check_goods_exist('barCode', $row[3]) && str_alert(-1, "$sku 商品条码已使用过");
        !isset($this->category[$row[4]]) && str_alert(-1, "$sku 商品分类不存在");
        (!is_numeric($row[5]) || $row[5] <= 0) && str_alert(-1, "$sku 规格型号输入有误");
        !isset($this->unit[$row[6]]) && str_alert(-1, "$sku 计量单位不存在");
        !isset($this->storage[$row[7]]) && str_alert(-1, "$sku 首选仓库不存在");
        !empty($row[8]) && (!is_numeric($row[8]) || $row[8] < 1) && str_alert(-1, "$sku 最低库存输入有误");
        !empty($row[9]) && (!is_numeric($row[9]) || $row[9] < 1) && str_alert(-1, "$sku 最高库存输入有误");
        !empty($row[10]) && (!is_numeric($row[10]) || $row[10] <= 0) && str_alert(-1, "$sku 预计采购价输入有误");
        (!is_numeric($row[11]) || $row[11] <= 0) && str_alert(-1, "$sku 零售价输入有误");
        !empty($row[12]) && (!is_numeric($row[12]) || $row[12] <= 0) && str_alert(-1, "$sku 批发价输入有误");
        !empty($row[13]) && (!is_numeric($row[13]) || $row[13] <= 0) && str_alert(-1, "$sku 会员价输入有误");
        !empty($row[14]) && (!is_numeric($row[14]) || $row[14] <= 0) && str_alert(-1, "$sku 折扣率一（%）输入有误");
        !empty($row[15]) && (!is_numeric($row[15]) || $row[15] <= 0) && str_alert(-1, "$sku 折扣率二（%）输入有误");
        !empty($row[16]) && (!is_numeric($row[16]) || $row[16] <= 0) && str_alert(-1, "$sku 【长】输入有误");
        !empty($row[17]) && (!is_numeric($row[17]) || $row[17] <= 0) && str_alert(-1, "$sku 【宽】输入有误");
        !empty($row[18]) && (!is_numeric($row[18]) || $row[18] <= 0) && str_alert(-1, "$sku 【高】输入有误");
        !empty($row[21]) && (!is_numeric($row[21]) || $row[21] <= 0) && str_alert(-1, "$sku 申报价格输入有误");
        !empty($row[23]) && !$this->storage[$row[23]] && str_alert(-1, "$sku 的{$row[23]}仓库不存在");
        !empty($row[23]) && !empty($row[24]) && (!is_numeric($row[24]) || $row[24] <= 0) && str_alert(-1, "$sku $row[23]期初数量输入有误");
        !empty($row[23]) && !empty($row[25]) && (!is_numeric($row[25]) || $row[25] <= 0) && str_alert(-1, "$sku $row[23]成本输入有误");
        !empty($row[23]) && !empty($row[26]) && (!is_numeric($row[26]) || $row[26] <= 0) && str_alert(-1, "$sku $row[23]期初总价输入有误");
    }

    /**
     * 组装产品数据
     * @param array $data 数据列表
     * @return array
     * @author longli
     */
    private function assemblyGoods($data)
    {
        $goods = [];
        $goodsNo = '';
        // 组装数据，支持分仓
        foreach($data as $item)
        {
            $item = array_map(function($t) {
                return trim($t);
            }, $item);
            $tNo = $item[1];
            if($goodsNo != $tNo || empty($tNo))
            {
                if(!empty($tNo))
                    $goodsNo = $tNo;
                if(!empty($goodsNo))
                    $goods[$goodsNo][] = $item;
            }

        }
        return $goods;
    }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */